<template>
  <view style="height: 100%">
      <dropdownmenu
          :dropDownMenuTitle="dropDownMenuTitle"
          style="width: 100%"
          :dropDownMenuGradeData="grades"
          :dropDownMenuSubjectData="subjects"
          :dropDownMenuDispartData="disparts"
          :dropDownMenuOrderType="ordertypes"
          :selectConfig="selectConfig"            
          @selectGradeItem="selectGradeItem"
          @selectSubjectItem="selectSubjectItem"
          @selectDispartItem="selectDispartItem"
          @selectOrderItem="selectOrderItem"
      />
      <view class="search-bar">
          <icon class="weui-icon-search_in-box" type="search" size="14"></icon>
          <input placeholder="请输入句块内容" @input="inputChange"/>
          <button type="primary" @click="queryBooks">查詢</button>
      </view>
      <view class="header-bg"></view>
      <scroll-view :scroll-y="true" :scroll-x="false" class="scroll" @scrolltolower="bindlower">
            <view class="book-content">
              <view class="list">
                <view class="item">
                    <view class="image">
                        <image src="/static/images/chunks.png" />
                    </view>
                    <view class="content">
                        <text class="h1" style="margin-left:30%">{{ banner.productTitle }}</text>   
                        <text class="p myp" style="margin-left:30%">
                          {{ banner.amount<=0?'免费':'￥'+banner.amount }}
                        </text>
                    </view>
                    <view class="number">
                        <view class="sum">{{ banner.jkNum }}张卡片</view>                        
                        <button class="weui-btn" style="top:60%" @tap="buyNow" :data-id="banner.id">下单</button>
                    </view>
                </view>
              </view>
              <view class="wuge" v-if="allShops == '' || allShops.length == 0">没有任何卡片信息</view>            
                <view class="list" v-for="(item, index) in allShops" :key="index">
                    <view class="item">
                        <view class="content">
                            <text class="h1" @tap="toDetail" :data-id="item.id">{{ item.materialName }}</text>
                            <text class="p pp">
                              卡包：
                              <span @tap="toDetailHH" :data-id="item.version">
                                {{ item.version }}
                              </span>
                            </text>
                            <text class="p ppp" @tap="toDetail" :data-id="item.id">{{ '关键词：'+item.materialKey }}</text>
                            <text class="p myp" @tap="toDetail" :data-id="item.id">
                                {{ item.isFree==1?'免费':'￥'+item.amount }}&nbsp;&nbsp;&nbsp;&nbsp;{{ item.region==0?'':item.region }}&nbsp;&nbsp;{{ item.age==0?'':item.age }}{{ item.gradeName }}{{ item.semesterName }}{{ item.subjectName }}
                            </text>
                        </view>
                        <view class="number">
                            <button class="weui-btn1" @tap="collect" :data-id="item.id">收藏</button>
                        </view>
                    </view>
                </view>
            </view>
        </scroll-view>        
  </view>
</template>

<script>
var config = require('../../config.js');
var http = require('../../utils/httpHelper.js');
var util = require('../../utils/util.js');
import dropdownmenu from '@/components/dropdownmenu/dropdownmenu';
import wx from 'weixin-js-sdk';
export default {
    components: {
      dropdownmenu
    },
    data() {
      return {
          inputValue:'',
          allShops: [],
          userId: 0,
          isLogin: false,
          sumPrice: 0,
          timer: {},
          grades: [],
          curGrade: 0,
          subjects: [],
          curSubject: 0,
          disparts: [],
          curDispart: 0,
          pxType: '',
          curSemester: 0,
          curVersion: '',
          selectConfig: {},
          ordertypes: [{id:0,title:'无排序'},{id:1,title:'最新排序'}],
          shopPage: {
              current: 1,
              pageSize: 10,
              total: 0
          },
          dropDownMenuTitle: ['全部年级', '全部学科', '全部分册','无排序'],    
          indicatorDots: false,
          //是否显示面板指示点
          autoplay: false,
          //是否自动切换
          current: 0,
          //当前所在index
          interval: 0,
          //自动切换时间
          duration: 200,
          //滑动时间
          clas: ['action'],          
          banner: {},
          bannerId: null
      };
    },
    onLoad: function (options) {
        var that = this;
        let userInfo = uni.getStorageSync('user');
        if (userInfo != null && userInfo != undefined && userInfo != {} && userInfo != '') {
          that.setData({
              isLogin: true,
              userId: userInfo.userId
          });
        } else {
            uni.setStorageSync('inviteId', options.inviteId);
        }
        that.shopPage.current = 1;
        that.queryGrades();
        that.querySubjects();
        that.queryDisparts();
        that.bannerId = options.id;
    },
    onShow: function () {
        var that = this;
        that.shopPage.current = 1;
        this.getMaterialjkList(function (list) {
            that.setData({
                allShops: list
            });
        });
    },
    methods: {
        async getMoreData() {
            var that = this;
            that.shopPage.current++;
            that.getMaterialjkList(function (list) {
                let yList = that.allShops;
                yList = yList.concat(list);
                that.setData({
                    allShops: yList
                });
            });
        },
        getMaterialjkList: function (callback) {
            var that = this;
            http.httpGet(
                config.clubApi.getBannerInfo,
                {
                    id: that.bannerId
                },
                function (resB) {
                    if (resB.code == '200') {
                        that.banner = resB.data;
                        that.curVersion = resB.data.productTitle;
                        http.httpPost(
                            config.clubApi.getMaterialjkList,
                            {
                                materialName: that.inputValue,
                                pageNo: that.shopPage.current,
                                pageSize: that.shopPage.pageSize,
                                grade: that.curGrade,
                                subject: that.curSubject,
                                age: that.curDispart,
                                semester: that.curSemester,
                                version: that.curVersion,
                                pxType: that.pxType,
                                appid: config.APPID
                            },
                            function (res) {
                                if (res.code == '200') {
                                    var list = res.data.pageData;
                                    if (typeof callback == 'function') {
                                        callback(list);
                                    }
                                }
                            }
                        );
                    }
                }
            );
            
        },
        toDetail: function (e) {
            var idParam = e.currentTarget.dataset.id;
            let userInfo = uni.getStorageSync('user');
            if (userInfo) {
              uni.navigateTo({
                  url: '../material/detail/index?id=' + idParam +'&inviteId=' + userInfo.userId
              });
            }else {
              uni.navigateTo({
                url: '../material/detail/index?id=' + idParam
              });
            }
        },        
        toDetailHH: function (e) {
          var idParamStr = e.currentTarget.dataset.id;
          var that = this;
          that.setData({
                cursemester: '0',
                curGrade: '0',
                curSemester: '0',
                curSubject: '0',
                dropDownMenuTitle: ['全部年级', '全部学科', '全部分册','无排序'],
                curVersion: idParamStr
          });
          that.shopPage.current = 1;
          that.getMaterialjkList(function (list) {
              that.setData({
                  allShops: list
              });
          });
        },
        buyNow: function (e) {
            if (this.isLogin && uni.getStorageSync('user')) {
                this.settlement(e);
            } else {
                uni.switchTab({
                    url: '/pages/user/index'
                });
            }
        },
        settlement: function (e) {
            var idParam = e.currentTarget.dataset.id;
            var data = {
                appId: config.APPID,
                bannerId: idParam,                
                userId: this.userId,
                amount: this.banner.amount
            };
            http.httpPut(config.clubApi.createOrderjk, data, function (res) {
                if (res.code == '200') {
                  if (data.amount>0) {
                    try {
                        let params = res.data;
                        WeixinJSBridge.invoke('getBrandWCPayRequest', params, function (res) {
                            if (res.err_msg == 'get_brand_wcpay_request:ok') {
                                uni.showToast({
                                    title: '支付成功',
                                    icon: 'none',
                                    duration: 3000
                                });
                            } else {
                                uni.showToast({
                                    title: '支付失败',
                                    icon: 'none',
                                    duration: 3000
                                });
                            }
                        });
                    } catch (f) {
                        if (res.msg) {
                            uni.showToast({
                                title: res.msg,
                                icon: 'none',
                                duration: 2000
                            });
                        }
                    }
                  }else {
                    if (res.msg) {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none',
                            duration: 2000
                        });
                    }
                  }
                }
            }); 
        },
        collect: function (e) {
            var idParam = e.currentTarget.dataset.id;
            var data = {
                appId: config.APPID,
                materialId: idParam,                
                userId: this.userId
            };
            http.httpPut(config.clubApi.createCollectjk, data, function (res) {
                uni.showToast({
                    title: res.msg,
                    icon: 'none',
                    duration: 3000
                });
            });
        },
        //处理分页
        bindlower: function (e) {
          if(this.timer != null){
            clearTimeout(this.timer)
          }
          this.timer = setTimeout(()=>{
            this.getMoreData();
          },500)
        },
        inputChange:function(e) {
          this.inputValue = e.detail.value;
        },
        queryBooks: function (e) {
          var that = this;
            http.httpPost(
                config.clubApi.getMaterialjkList,
                {
                    materialName: that.inputValue,
                    pageNo: that.shopPage.current,
                    pageSize: that.shopPage.pageSize,
                    grade: that.curGrade,
                    subject: that.curSubject,
                    age: that.curDispart,
                    semester: that.curSemester,
                    version: that.curVersion,
                    pxType: that.pxType,
                    appid: config.APPID
                },
                function (res) {
                    if (res.code == '200') {
                        var list = res.data.pageData;
                        that.setData({
                            allShops: list
                        });
                    }
                }
            );
        },   
        queryGrades: function (e) {
            var that = this;
            http.httpGet(
                config.clubApi.getGrades,{},
                function (res) {
                    if (res.code == '200') {
                        var grades = [
                            {
                                id: 0,
                                title: '全部年级'
                            }
                        ];
                        for (var i = 0; i < res.data.length; i++) {
                            grades.push({
                                id: res.data[i].dictValue,
                                title: res.data[i].dictLabel
                            });
                        }
                        that.setData({
                            grades: grades
                        });
                    }
                }
            );
        },
        querySubjects: function (e) {
            var that = this;
            http.httpGet(
                config.clubApi.getSubjects,{},
                function (res) {
                    if (res.code == '200') {
                        var subjects = [
                            {
                                id: 0,
                                title: '全部学科'
                            }
                        ];
                        for (var i = 0; i < res.data.length; i++) {
                          if (res.data[i].dictLabel==='英语') {
                            subjects.push({
                                id: res.data[i].dictValue,
                                title: res.data[i].dictLabel
                            });
                          }
                        }
                        that.setData({
                            subjects: subjects
                        });
                    }
                }
            );
        },
        queryDisparts: function (e) {
            var that = this;
            http.httpGet(
                config.clubApi.getAges,{},
                function (res) {
                    if (res.code == '200') {
                        var disparts = [
                            {
                                id: 0,
                                title: '全部分册'
                            }
                        ];
                        for (var i = 0; i < res.data.length; i++) {
                            disparts.push({
                                id: res.data[i],
                                title: res.data[i]
                            });
                        }
                        that.setData({
                            disparts: disparts
                        });
                    }
                }
            );
        },
        selectGradeItem: function (e) {
            var that = this;
            that.setData({
                curGrade: e.detail.selectedId,
                curSemester: 0,
                curVersion: ''
            });
            that.selectConfig.curGrade = e.detail.selectedId;
            that.dropDownMenuTitle[0] = e.detail.selectedTitle;
            that.shopPage.current = 1;
            this.getMaterialjkList(function (list) {
                that.setData({
                    allShops: list
                });
            });
        },
        selectSubjectItem: function (e) {
            var that = this;
            that.setData({
                curSubject: e.detail.selectedId,
                curSemester: 0,
                curVersion: ''
            });
            that.selectConfig.curSubject = e.detail.selectedId;
            that.dropDownMenuTitle[1] = e.detail.selectedTitle;
            that.shopPage.current = 1;
            this.getMaterialjkList(function (list) {
                that.setData({
                    allShops: list
                });
            });
        },
        selectDispartItem: function (e) {
            var that = this;
            that.setData({
                curDispart: e.detail.selectedId,
                curSemester: 0,
                curVersion: ''
            });
            that.selectConfig.curDispart = e.detail.selectedId;
            that.dropDownMenuTitle[2] = e.detail.selectedTitle;
            that.shopPage.current = 1;
            this.getMaterialjkList(function (list) {
                that.setData({
                    allShops: list
                });
            });
        },
        selectOrderItem: function (e) {
            var that = this;            
            that.setData({
                pxType: e.detail.selectedId
            });
            that.shopPage.current = 1;
            this.getMaterialjkList(function (list) {
                that.setData({
                    allShops: list
                });
            });
        },           
    }
};
</script>
<style lang="scss">
@import './index.scss';
</style>
